// Copyright (c) 2025, qiushike and contributors
// For license information, please see license.txt

// frappe.ui.form.on("Subcontracting Service Price", {
// 	refresh(frm) {

// 	},
// });

frappe.ui.form.on("Subcontracting Service Price", {
	refresh(frm) {
	},
	
	// 当用户修改阶梯价格明细时，按最小数量排序
	subcontracting_step_price_item: function(frm) {
		if (frm.doc.subcontracting_step_price_item && frm.doc.subcontracting_step_price_item.length > 0) {
			frm.doc.subcontracting_step_price_item.sort((a, b) => {
				return a.min_qty - b.min_qty;
			});
			frm.refresh_field('subcontracting_step_price_item');
		}
	}
});

// 子表行事件
frappe.ui.form.on('Subcontracting Step Price Item', {
	// 当最小数量或最大数量变化时，进行简单验证
	min_qty: function(frm, cdt, cdn) {
		validate_min_max_qty(frm, cdt, cdn);
	},
	
	max_qty: function(frm, cdt, cdn) {
		validate_min_max_qty(frm, cdt, cdn);
	},
	
	// 当新增行时，自动设置最小数量
	subcontracting_step_price_item_add: function(frm, cdt, cdn) {
		let row = locals[cdt][cdn];
		let rows = frm.doc.subcontracting_step_price_item || [];
		
		// 如果是第一行，则设置最小数量为0
		if (rows.length === 1) {
			frappe.model.set_value(cdt, cdn, 'min_qty', 0);
		}
		// 如果不是第一行，则设置最小数量为上一行的最大数量
		else if (rows.length > 1) {
			// 按最小数量排序
			rows.sort((a, b) => a.min_qty - b.min_qty);
			
			// 找到当前行的索引
			let currentIndex = rows.findIndex(r => r.name === row.name);
			
			// 如果不是第一行，则设置最小数量为上一行的最大数量
			if (currentIndex > 0) {
				let prevRow = rows[currentIndex - 1];
				if (prevRow.max_qty) {
					frappe.model.set_value(cdt, cdn, 'min_qty', prevRow.max_qty);
				}
			}
		}
	}
});

// 验证最小数量和最大数量
function validate_min_max_qty(frm, cdt, cdn) {
	let row = locals[cdt][cdn];
	
	// 检查最小数量是否小于最大数量
	if (row.min_qty && row.max_qty && parseFloat(row.min_qty) >= parseFloat(row.max_qty)) {
		frappe.msgprint(__("Min Qty must be less than Max Qty in row {0}", [row.idx]));
		frappe.model.set_value(cdt, cdn, 'min_qty', 0);
		frappe.model.set_value(cdt, cdn, 'max_qty', 0);
		return;
	}
	
	// 获取所有行并按最小数量排序
	let rows = frm.doc.subcontracting_step_price_item || [];
	rows.sort((a, b) => a.min_qty - b.min_qty);
	
	// 找到当前行的索引
	let currentIndex = rows.findIndex(r => r.name === row.name);
	
	// 如果不是第一行，检查最小数量是否等于上一行的最大数量
	if (currentIndex > 0) {
		let prevRow = rows[currentIndex - 1];
		if (row.min_qty && prevRow.max_qty && parseFloat(row.min_qty) !== parseFloat(prevRow.max_qty)) {
			frappe.msgprint(__("Min Qty must be equal to Max Qty of previous row"));
			frappe.model.set_value(cdt, cdn, 'min_qty', prevRow.max_qty);
		}
	}
	
	// 如果不是最后一行，检查最大数量是否等于下一行的最小数量
	if (currentIndex < rows.length - 1) {
		let nextRow = rows[currentIndex + 1];
		if (row.max_qty && nextRow.min_qty && parseFloat(row.max_qty) !== parseFloat(nextRow.min_qty)) {
			frappe.msgprint(__("Max Qty must be equal to Min Qty of next row"));
			frappe.model.set_value(cdt, cdn, 'max_qty', nextRow.min_qty);
		}
	}
}
